package com.yuanrui.subject.domain.service.impl;

import com.alibaba.fastjson.JSON;
import com.yuanrui.subject.common.enums.IsDeletedFlagEnum;
import com.yuanrui.subject.domain.convert.SubjectCategoryConverter;
import com.yuanrui.subject.domain.entity.SubjectCategoryBO;
import com.yuanrui.subject.domain.entity.SubjectLabelBo;
import com.yuanrui.subject.domain.service.SubjectCategoryDomainService;
import com.yuanrui.subject.domain.util.CacheUtil;
import com.yuanrui.subject.infra.basic.entity.SubjectCategory;
import com.yuanrui.subject.infra.basic.entity.SubjectLabel;
import com.yuanrui.subject.infra.basic.entity.SubjectMapping;
import com.yuanrui.subject.infra.basic.service.SubjectCategoryService;
import com.yuanrui.subject.infra.basic.service.impl.SubjectLabelServiceImpl;
import com.yuanrui.subject.infra.basic.service.impl.SubjectMappingServiceImpl;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;

@Service
@Slf4j
public class SubjectCategoryDomainServiceImpl implements SubjectCategoryDomainService {

    @Resource
    private SubjectCategoryService subjectCategoryService;
    @Resource
    private SubjectMappingServiceImpl subjectMappingService;
    @Resource
    private SubjectLabelServiceImpl subjectLabelService;

    @Resource
    private ThreadPoolExecutor labelThreadPool;

    @Resource
    private CacheUtil cacheUtil;


    @Override
    public Boolean add(SubjectCategoryBO subjectCategoryBO) {
        if (log.isInfoEnabled()) {
            log.info("SubjectCategoryController.add.bo:{}", JSON.toJSONString(subjectCategoryBO));
        }
        SubjectCategory subjectCategory = SubjectCategoryConverter.INSTANCE
                .convertBoToCategory(subjectCategoryBO);
        subjectCategory.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getCode());
        int insert = subjectCategoryService.insert(subjectCategory);
        return insert > 0;
    }

    @Override
    public List<SubjectCategoryBO> queryCategory(SubjectCategoryBO subjectCategoryBO) {
        SubjectCategory subjectCategory = SubjectCategoryConverter.INSTANCE
                .convertBoToCategory(subjectCategoryBO);
        subjectCategory.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getCode());
        List<SubjectCategory> subjectCategoryList = subjectCategoryService.queryCategory(subjectCategory);
        List<SubjectCategoryBO> boList = SubjectCategoryConverter.INSTANCE
                .convertBoToCategory(subjectCategoryList);
        if (log.isInfoEnabled()) {
            log.info("SubjectCategoryController.queryPrimaryCategory.boList:{}",
                    JSON.toJSONString(boList));
        }
        boList.forEach(bo -> {
            Integer subjectCount = subjectCategoryService.querySubjectCount(bo.getId());
            bo.setCount(subjectCount);
        });
        return boList;

    }

    @Override
    public Boolean update(SubjectCategoryBO subjectCategoryBO) {
        SubjectCategory subjectCategory = SubjectCategoryConverter.INSTANCE
                .convertBoToCategory(subjectCategoryBO);
        int count = subjectCategoryService.update(subjectCategory);
        return count > 0;
    }

    @Override
    public Boolean delete(SubjectCategoryBO subjectCategoryBO) {
        SubjectCategory subjectCategory = SubjectCategoryConverter.INSTANCE
                .convertBoToCategory(subjectCategoryBO);
        subjectCategory.setIsDeleted(IsDeletedFlagEnum.DELETED.getCode());
        int count = subjectCategoryService.update(subjectCategory);
        return count > 0;
    }

    @SneakyThrows
    @Override
    public List<SubjectCategoryBO> queryCategoryAndLabel(SubjectCategoryBO subjectCategoryBO) {
        String cacheKey = "CategoryAndLabel_" + subjectCategoryBO.getId();
        //函数式编程，通过传入String类型的key，返回List<V>类型的结果，通过function.apply()方法获取结果
        return cacheUtil.getResult(cacheKey, SubjectCategoryBO.class, (key) -> getSubjectCategoryBOS(subjectCategoryBO.getId()));

//        List<SubjectCategoryBO> subjectCategoryBOS = new LinkedList<>();
//        if (StringUtils.isBlank(content)) {
//            subjectCategoryBOS = getSubjectCategoryBOS(subjectCategoryBO.getId());
//            localCache.put(cacheKey, JSON.toJSONString(subjectCategoryBOS));
//        } else {
//            subjectCategoryBOS = JSON.parseArray(content, SubjectCategoryBO.class);
//        }
//        //查询当前分类下所有分类
//        return subjectCategoryBOS;


//        //使用FutureTask线程池查询当前分类下所有标签
//        List<FutureTask<Map<Long, List<SubjectLabelBo>>>> futureTasks = new LinkedList<>();
//        Map<Long, List<SubjectLabelBo>> resultAllMap = new HashMap<>();
//        //线程池并发查询标签
//        subjectCategoryBOS.forEach(bo -> {
//            FutureTask<Map<Long, List<SubjectLabelBo>>> future = new FutureTask<>(() ->
//                    getLabelBoList(bo));
//            futureTasks.add(future);
//            labelThreadPool.submit(future);
//        });
//        //获取线程池查询结果
//        for (FutureTask<Map<Long, List<SubjectLabelBo>>> futureTask : futureTasks) {
//            Map<Long, List<SubjectLabelBo>> resultMap = futureTask.get();
//            if (CollectionUtils.isEmpty(resultMap)) {
//                continue;
//            }
//            resultAllMap.putAll(resultMap);
//            //将标签信息放入分类中
//            subjectCategoryBOS.forEach(bo -> {
//                bo.setLabelBoList(resultAllMap.get(bo.getId()));
//            });
//        }
        //查询当前分类下所有标签
    }

    @SneakyThrows
    private List<SubjectCategoryBO> getSubjectCategoryBOS(Long categoryId) {
        SubjectCategory subjectCategory = new SubjectCategory();
        subjectCategory.setParentId(categoryId);
        subjectCategory.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getCode());
        List<SubjectCategory> subjectCategoryList = subjectCategoryService.queryCategory(subjectCategory);
        if (log.isInfoEnabled()) {
            log.info("SubjectCategoryController.queryPrimaryCategory.boList:{}",
                    JSON.toJSONString(subjectCategoryList));
        }
        List<SubjectCategoryBO> subjectCategoryBOS = SubjectCategoryConverter.INSTANCE.convertBoToCategory(subjectCategoryList);
        //使用CompletableFuture查询当前分类下所有标签,异步查询，每一个分类一个线程
        Map<Long, List<SubjectLabelBo>> map = new HashMap<>();
        List<CompletableFuture<Map<Long, List<SubjectLabelBo>>>> completableFutureList = subjectCategoryBOS.stream().map(category ->
                CompletableFuture.supplyAsync(() ->
                        getLabelBoList(category), labelThreadPool)).toList();

        //使用CompletableFuture查询当前分类下所有标签
        for (CompletableFuture<Map<Long, List<SubjectLabelBo>>> mapCompletableFuture : completableFutureList) {
            Map<Long, List<SubjectLabelBo>> labelMap = mapCompletableFuture.get();
            if (CollectionUtils.isEmpty(labelMap)) {
                continue;
            }
            map.putAll(labelMap);
        }
        subjectCategoryBOS.forEach(bo -> {
            bo.setLabelBoList(map.get(bo.getId()));
        });
        return subjectCategoryBOS;
    }

    private Map<Long, List<SubjectLabelBo>> getLabelBoList(SubjectCategoryBO bo) {
        if (log.isInfoEnabled()) {
            log.info("SubjectCategoryController.getLabelBoList.bo:{}", JSON.toJSONString(bo));
        }
        Map<Long, List<SubjectLabelBo>> labelMap = new HashMap<>();
        SubjectMapping subjectMapping = new SubjectMapping();
        subjectMapping.setCategoryId(bo.getId());
        List<SubjectMapping> subjectMappings = subjectMappingService.queryLabelByCategoryId(subjectMapping);
        if (CollectionUtils.isEmpty(subjectMappings)) {
            return null;
        }
        List<Long> labelList = subjectMappings.stream().map(SubjectMapping::getLabelId).toList();
        List<SubjectLabel> subjectLabels = subjectLabelService.batchQueryById(labelList);
        List<SubjectLabelBo> labelBos = new LinkedList<>();
        subjectLabels.forEach(labelBo -> {
            SubjectLabelBo subjectLabelBo = new SubjectLabelBo();
            subjectLabelBo.setId(labelBo.getId());
            subjectLabelBo.setLabelName(labelBo.getLabelName());
            subjectLabelBo.setIsDeleted(labelBo.getIsDeleted());
            subjectLabelBo.setSortNum(labelBo.getSortNum());
            labelBos.add(subjectLabelBo);
        });
        labelMap.put(bo.getId(), labelBos);
        return labelMap;
    }


}
